package com.atguigu.medical.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.medical.realtime.app.BaseApp;
import com.atguigu.medical.realtime.bean.TradePatientConsultationPayBean;
import com.atguigu.medical.realtime.common.Constant;
import com.atguigu.medical.realtime.function.AsyncDimFunction;
import com.atguigu.medical.realtime.util.DateUtil;
import com.atguigu.medical.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * @Author lzc
 * @Date 2023/4/28 14:47
 */
public class DwsTradePatientConsultationPayWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsTradePatientConsultationPayWindow().init(
            40015,
            2,
            "DwsTradePatientConsultationPayWindow",
            Constant.TOPIC_DWD_TRADE_CONSULTATION_FEE_PAY_SUCCESS
        );
        
    }
    
    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 把数据封装为 pojo 类型
        SingleOutputStreamOperator<TradePatientConsultationPayBean> beanStream = parseToPojo(stream);
        // 2. 补充维度: 需要先补充患者的性别和年龄,才能聚和
         beanStream = joinDims(beanStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<TradePatientConsultationPayBean> resultStream = windowAndAgg(beanStream);
        // 4. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
    }
    
    private SingleOutputStreamOperator<TradePatientConsultationPayBean> joinDims(
        SingleOutputStreamOperator<TradePatientConsultationPayBean> stream) {
        
        
        return AsyncDataStream.unorderedWait(
            stream,
            new AsyncDimFunction<TradePatientConsultationPayBean>() {
                @Override
                public String getTable() {
                    return "dim_patient";
                }
                
                @Override
                public String getId(TradePatientConsultationPayBean bean) {
                    return bean.getPatientId();
                }
                
                @Override
                public void addDim(TradePatientConsultationPayBean bean, JSONObject dim) {
                    bean.setPatientSex(dim.getInteger("GENDER") == 101 ? "男": "女");
                    // flink cdc 读取 Date 类型的数据的时候,把 Date 转成了 Long 类型的天数(从 1970 1 1 日计算的天数)来存储.
                    long age = (System.currentTimeMillis() - dim.getLong("BIRTHDAY") * 24 * 60 * 60 * 1000) / 1000 / 60 / 60 / 24 / 365;
                    bean.setPatientAge((int) age);
                }
            },
            60,
            TimeUnit.SECONDS
        );
    }
    
    
    private void writeToClickHouse(SingleOutputStreamOperator<TradePatientConsultationPayBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_patient_consultation_pay_window", TradePatientConsultationPayBean.class));
    }
    
    private SingleOutputStreamOperator<TradePatientConsultationPayBean> windowAndAgg(
        SingleOutputStreamOperator<TradePatientConsultationPayBean> beanStream) {
        return beanStream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradePatientConsultationPayBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((obj, ts) -> obj.getTs())
                    .withIdleness(Duration.ofSeconds(60))
            )
            .keyBy(obj -> obj.getPatientSex() + "_" + obj.getPatientAge())
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradePatientConsultationPayBean>() {
                    @Override
                    public TradePatientConsultationPayBean reduce(TradePatientConsultationPayBean value1,
                                                              TradePatientConsultationPayBean value2) throws Exception {
                        value1.setConsultationPayCt(value1.getConsultationPayCt() + value2.getConsultationPayCt());
                        value1.setConsultationPayAmount(value1.getConsultationPayAmount().add(value2.getConsultationPayAmount()));
                        return value1;
                    }
                },
                new ProcessWindowFunction<TradePatientConsultationPayBean, TradePatientConsultationPayBean, String, TimeWindow>() {
                    @Override
                    public void process(String doctorId,
                                        Context ctx,
                                        Iterable<TradePatientConsultationPayBean> elements,
                                        Collector<TradePatientConsultationPayBean> out) throws Exception {
                        TradePatientConsultationPayBean bean = elements.iterator().next();
    
                        bean.setStt(DateUtil.tsToDateTime(ctx.window().getStart()));
                        bean.setEdt(DateUtil.tsToDateTime(ctx.window().getEnd()));
                        bean.setTs(System.currentTimeMillis());
    
                        out.collect(bean);
                    }
                }
            );
        
    }
    
    private SingleOutputStreamOperator<TradePatientConsultationPayBean> parseToPojo(DataStreamSource<String> stream) {
        return stream
            .map(new MapFunction<String, TradePatientConsultationPayBean>() {
                @Override
                public TradePatientConsultationPayBean map(String value) throws Exception {
                    JSONObject obj = JSON.parseObject(value);
                    
                    return TradePatientConsultationPayBean.builder()
                        .patientId(obj.getString("patient_id"))
                        .consultationPayCt(1L)
                        .consultationPayAmount(obj.getBigDecimal("payment_amount"))
                        .ts(obj.getLong("ts"))
                        .build();
                }
            });
    }
}
